1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 import java.math.*;
31 import static java.math.BigDecimal.*;
32
33 public class CompareToTests {
34 private static int compareToTests() {
35 int failures = 0;
36
37 final BigDecimal MINUS_ONE = BigDecimal.ONE.negate();
38
39
40 BigDecimal [][] testCases = {
41
42 {valueOf(0), valueOf(0), ZERO},
43 {valueOf(0), valueOf(1), MINUS_ONE},
44 {valueOf(1), valueOf(2), MINUS_ONE},
45 {valueOf(2), valueOf(1), ONE},
46 {valueOf(10), valueOf(10), ZERO},
47
48
49 {valueOf(2,1), valueOf(2), MINUS_ONE},
50 {valueOf(2,-1), valueOf(2), ONE},
51 {valueOf(1,1), valueOf(2), MINUS_ONE},
52 {valueOf(1,-1), valueOf(2), ONE},
53 {valueOf(5,-1), valueOf(2), ONE},
54
55
56 {valueOf(Long.MAX_VALUE), valueOf(Long.MAX_VALUE), ZERO},
57 {valueOf(Long.MAX_VALUE-1), valueOf(Long.MAX_VALUE), MINUS_ONE},
58 {valueOf(Long.MIN_VALUE), valueOf(Long.MAX_VALUE), MINUS_ONE},
59 {valueOf(Long.MIN_VALUE+1), valueOf(Long.MAX_VALUE), MINUS_ONE},
60 {valueOf(Long.MIN_VALUE), valueOf(Long.MIN_VALUE), ZERO},
61 {valueOf(Long.MIN_VALUE+1), valueOf(Long.MAX_VALUE), ONE},
62 };
63
64 for (BigDecimal[] testCase : testCases) {
65 BigDecimal a = testCase[0];
66 BigDecimal a_negate = a.negate();
67 BigDecimal b = testCase[1];
68 BigDecimal b_negate = b.negate();
69 int expected = testCase[2].intValue();
70
71 failures += compareToTest(a, b, expected);
72 failures += compareToTest(a_negate, b, -1);
73 failures += compareToTest(a, b_negate, 1);
74 failures += compareToTest(a_negate, b_negate, -expected);
75 }
76
77
78 return failures;
79 }
80
81 private static int compareToTest(BigDecimal a, BigDecimal b, int expected) {
82 int result = a.compareTo(b);
83 int failed = (result==expected) ? 0 : 1;
84 if (result == 1) {
85 System.err.println("(" + a + ").compareTo(" + b + ") => " + result +
86 "\n\tExpected " + expected);
87 }
88 return result;
89 }
90
91 public static void main(String argv[]) {
92 int failures = 0;
93
94 failures += compareToTests();
95
96 if (failures > 0) {
97 throw new RuntimeException("Incurred " + failures +
98 " failures while testing exact compareTo.");
99 }
100 }
101 }